# -*- encoding:utf8 -*-
import re
from datetime import datetime, tzinfo, timedelta


def i2t(second):
    """int类型转换为时间格式
    510 --> "8:30"
    """
    if second > 0:
        return "%02d:%02d" % (second / 60, second % 60)
    else:
        return '00:00'


def t2i(tstr):
    """时间格式转换为int类型
    "8:30" --> 510
    """
    if not tstr:
        return 0
    elif tstr == '0':
        return 0
    else:
        ls = tstr.split(':')
        return int(ls[0]) * 60 + int(ls[1])

def t2h(tstr):
    return i2h(t2i(tstr))

def h2t(hour):
    return i2t(int(float(hour)*60))

def t2day(tstr):
    return  i2day(t2i(tstr))
def day2t(days):
    return i2t(float(days)*8*60)

def day2i(days):
    return int(float(days)*8*60)

def i2h(minite):
    return '%.2f'%(minite/60.0)

def i2day(minite):
    """int类型(分钟数)转换为天，每天按照8小时计算
    该函数用于多半用于对外显示
    """
    if minite == 0:
        return '0'
    else:
        return '%.2f'%( minite / (8.0 * 60))


def td2i(timedelta):
    """时间间隔----> 分钟数间隔
    timedelta ---> int
    """
    return timedelta.days * 60 * 24 + timedelta.seconds / 60


def ts2is(src):
    """ 时间段字符串，转换为(int,int)
    "8:30-12:30"  ---> (1234,2324)
    """
    mt = re.match(r"(.*)-(.*)", src)
    if mt:
        return tuple((t2i(s) for s in src.split("-")))
    else:
        return None

def td2i(td):
    """timedelta   -----> minites
    """
    return td.seconds / 60

def is2ts(ispan):
    """(int,int)转换为时间段字符串
    (1234,2324) ---> "8:30-12:30" 
    """
    if ispan:
        return "%s-%s" % (i2t(ispan[0]), i2t(ispan[1]))
    else:
        return ""


def date2str(date):
    return date.strftime('%Y-%m-%d')


def str2date(datestr):
    dt = datetime.strptime(datestr, '%Y-%m-%d')
    return dt.date()



#def get_time(dtstr):
    #"""dtstr:'2015-10-03 08:30'
    #"""
    #return dtstr.split()[1]


def dt2str(dt):
    return dt.strftime('%Y-%m-%d %H:%M')


def str2dt(dtstr):
    return datetime.strptime(dtstr, '%Y-%m-%d %H:%M')


class utc(tzinfo):
    def utcoffset(self, datetime):
        return timedelta(0)

    def dst(self, dt):
        # a fixed-offset class:  doesn't account for DST
        return timedelta(0)


class bj(tzinfo):
    def utcoffset(self, datetime):
        return timedelta(hours=8)

    def dst(self, dt):
        return timedelta(0)


def us2ls(us):
    """u'2016-01-12T00:30:00.000Z'
    """
    dt_obj = datetime.strptime(us, '%Y-%m-%dT%H:%M:00.000Z')
    utc_obj = dt_obj.replace(tzinfo=utc())
    bj_obj = utc_obj.astimezone(bj())
    return bj_obj.strftime('%Y-%m-%d %H:%M')

def ts2dls(start_time,end_time):
    """
    2015-10-01 08:30 
    2015-10-03 17:30
    转换为:2015-10-01,2015-10-02,2015-10-03
    """
    sto=str2dt(start_time)
    eto=str2dt(end_time)
    pos=sto
    out=[]
    while True:
        out.append(date2str(pos.date()))
        pos+=timedelta(days=1)
        if pos>eto:
            break
    return out